from rest_framework import serializers
from users.models import User, UserAddress, UserAvatar,Logo
from rest_framework.validators import UniqueValidator
import re

# 手机号码正则表达式
REGEX_MOBILE = r"^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"

# 用户注册序列化器--验证用户是否已存在、验证手机号码是否已存在、合法手机号、加密保存用户信息（password）
class UserRegisterSerializer(serializers.ModelSerializer):
    # 验证用户名是否存在
    username = serializers.CharField(
        label="用户名",
        help_text="用户名",
        required=True,
        allow_blank=False,
        validators=[UniqueValidator(queryset=User.objects.all(), message="用户已经存在")],
    )
    password = serializers.CharField(
        style={"input_type": "password"}, write_only=True, required=True, label="密码"
    )

    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {"password": {"write_only": True}}

    def create(self, validated_data):
        user = super(UserRegisterSerializer, self).create(validated_data=validated_data)
        user.set_password(validated_data["password"])
        user.save()
        return user

    def validate_mobile(self, mobile):
        # 是否已经注册
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError("用户已经存在")
        # 是否合法
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码非法")
        return mobile

    # 密码验证--目前只验证过短密码其它不做限制
    def validate_password(self, password):
        if len(password) >= 5:
            return password
        else:
            raise serializers.ValidationError("密码过短")


class UserBaseInfosUpdateSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["mobile", "email", "age"]


class OwnerForAddress(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username"]
        read_only_fields = ["id", "username"]


class GetUserAddressSerializer(serializers.ModelSerializer):
    owner = OwnerForAddress()

    class Meta:
        model = UserAddress
        fields = "__all__"
        read_only_fields = ["id", "owner"]

    def validated_is_defult(self, is_defult):
        if is_defult == True:
            for item in UserAddress.objects.all():
                item.is_defult = False
                item.save()

        return is_defult


class PostUserAdressSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAddress
        fields = "__all__"
        read_only_fields = ["id", "owner"]


class UserAvatarSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAvatar
        fields = "__all__"
        read_only_fields = ["id", "owner"]

class LogoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Logo
        fields = "__all__"
        